import { request } from "../../request/index.js";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabs: [
      {
        id: 0,
        value: "综合",
        isActive: true
      },
      {
        id: 1,
        value: "销量",
        isActive: false
      },
      {
        id: 2,
        value: "价格",
        isActive: false
      }
    ],
    goodsList: []
  },

  //接口参数
  QueryParams: {
    query: "",
    cid: "",
    pagenum: 1,
    pagesize: 10
  },

  //总页数
  totalPages: 1,

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.QueryParams.cid = options.cid;
    this.getGoodsList();
  },

  //获取商品列表数据
  async getGoodsList() {
    const res = await request({
      url: "/goods/search",
      data: this.QueryParams
    });
    //console.log(res);
    //给goods_list数组赋值
    //获取总条数
    const total = res.total;
    //计算总页数
    this.totalPages = Math.ceil(total / this.QueryParams.pagesize);
    console.log(this.totalPages);
    this.setData({
      //拼接数组
      // goodsList:res.goods
      goodsList: [...this.data.goodsList, ...res.goods]
    })
    //关闭下拉刷新窗口
    wx.stopPullDownRefresh();
  },


  //标题点击事件，从子组件传递过来
  handleTabsItemChange(e) {
    //1, 获取被点击的标题索引
    const { index } = e.detail;
    //2， 修改源数组
    let { tabs } = this.data;
    tabs.forEach((v, i) => i === index ? v.isActive = true : v.isActive = false)
    //3,赋值到data
    this.setData({
      tabs
    })

  },

  //页面上滑滚动条触底事件
  onReachBottom() {
    //console.log("触发触底了")
    //判断还有没有下一页
    if (this.QueryParams.pagenum >= this.totalPages) {
      //没有下一页数据了
      //console.log("没有下一页数据了");
      wx.showToast({
        title: '没有下一页数据了'
      });
    } else {
      // console.log('%c'+"有下一页数据");
      this.QueryParams.pagenum++;
      this.getGoodsList();
    }
  },

  //下拉刷新事件
  onPullDownRefresh(){
    console.log("下拉刷新事件！")
    //重置数组， 重置页码， 重新发送请求
    this.setData({
      goodsList:[]
    })
    this.QueryParams.pagenum=1;
    this.getGoodsList();
  }


})